package com.sheng.leetcode.year2022.swordfingeroffer.day20;

import org.junit.Test;

import java.util.Arrays;

/**
 * @author liusheng
 * @date 2022/09/19
 *<p>
 * 剑指 Offer 07. 重建二叉树<p>
 *<p>
 * 输入某二叉树的前序遍历和中序遍历的结果，请构建该二叉树并返回其根节点。<p>
 * 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。<p>
 *<p>
 * 示例 1:<p>
 * Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]<p>
 * Output: [3,9,20,null,null,15,7]<p>
 * <p>
 * 示例 2:<p>
 * Input: preorder = [-1], inorder = [-1]<p>
 * Output: [-1]<p>
 *<p>
 * 限制：<p>
 *<p>
 * 0 <= 节点个数 <= 5000<p>
 *<p>
 * 注意：本题与主站 105 题重复：<a href="https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/">...</a><p>
 *<p>
 * 来源：力扣（LeetCode）<p>
 * 链接：<a href="https://leetcode.cn/problems/zhong-jian-er-cha-shu-lcof">...</a><p>
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。<p>
 */
public class Sword0007 {

    @Test
    public void test01() {
//        int[] preorder = {3,9,20,15,7}, inorder = {9,3,15,20,7};
        int[] preorder = {-1}, inorder = {-1};
        TreeNode node = new Solution().buildTree(preorder, inorder);
        System.out.println(node);
    }
}
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length == 0) {
            return null;
        }
        int length = preorder.length;
        TreeNode node = new TreeNode(preorder[0]);
        // 寻找左结点
        int index = findIndex(preorder[0], inorder);
        // 从数组中寻找左子树的先序部分
        int[] leftPreorder = Arrays.copyOfRange(preorder, 1, 1 + index);
        // 从数组中寻找左子树的中序部分
        int[] leftInorder = Arrays.copyOfRange(inorder, 0, index);
        node.left = buildTree(leftPreorder, leftInorder);
        // 寻找右结点
        // 从数组中寻找右子树的先序部分
        int[] rightPreorder = Arrays.copyOfRange(preorder, 1 + index, length);
        // 从数组中寻找右子树的中序部分
        int[] rightInorder = Arrays.copyOfRange(inorder, 1 + index, length);
        node.right = buildTree(rightPreorder, rightInorder);
        return node;
    }

    public int findIndex(int n, int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == n) {
                return i;
            }
        }
        return -1;
    }
}

// Definition for a binary tree node.
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}
